import { createApp } from 'vue'
import App from './App.vue'

import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
import {createPinia} from "pinia";
import { useAppStore } from "./store/stroes"

const app = createApp(App)
const pinia = createPinia()

app.use(pinia)
app.use(ElementPlus)


async function initApp() {
    const appStore = useAppStore()

    // 清空再加载本地数据
    appStore.clearAllData()
    appStore.loadFromStorage()

    // 如果本地没有数据，就去后端拉取
    if (!appStore.hasTreeData || !appStore.hasUserConfigers || !appStore.hasSentenceData) {
        await fetchDataFromAPI(appStore)
    }

    console.log('✅ Store 初始化完成，开始挂载 Vue 应用')
    app.mount('#app')
}

async function fetchDataFromAPI(appStore) {
    const res = await fetch('http://127.0.0.1:5000/api/jsondata')
    if (!res.ok) throw new Error(`HTTP Error: ${res.status}`)

    const data = await res.json()
    appStore.setTreeData(data.treeData || [])
    appStore.setUserConfigers(data.userConfigers || [])
    appStore.setSentenceData(data.sentenceData || [])
    appStore.setInputData(data.inputData || {})
}

// 👇 启动前等待 store 初始化完成
initApp()
